package com.stxx.stiot2.job;

import com.stxx.framwork.utils.FluxUtils;
import com.stxx.framwork.utils.ObjectUtils;
import com.stxx.stiot2.domain.Terminal;
import com.stxx.stiot2.domain.cache.TerminalCache;
import com.stxx.stiot2.domain.ext.SignalEx;
import com.stxx.stiot2.external.InfluxdbServer;
import com.stxx.stiot2.external.RedisServer;
import com.stxx.stiot2.service.ProfileService;
import com.stxx.stiot2.service.TerminalService;
import com.stxx.stiot2.utils.SignalUtils;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.scheduling.annotation.Scheduled;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class PeriodStoreJob{
    @Inject
    ProfileService profileService;
    @Inject
    InfluxdbServer influxdbServer;
    @Inject
    TerminalService terminalService;

    @Scheduled(fixedRate = 1000)
    public void run() {
        List<SignalEx> list = profileService.periodSignals();
        if(list==null||list.isEmpty()) {return;}
        Long ts = System.currentTimeMillis();
        for (SignalEx signalEx : list) {
            if(SignalUtils.isTime(signalEx,ts)){
                List<TerminalCache> terminals = terminalService.queryGwAndCodeByProfile(signalEx.getProfileCode());
                if(terminals!=null){
                    Class<?> fieldType = FluxUtils.getType(signalEx.getFieldType());
                    for (TerminalCache terminal : terminals) {
                        Object curValue = terminalService.getLastValue(terminal.getCode(),signalEx.getCode());
                        if(curValue!=null){
                            Map<String,Object> map = new HashMap<>();
                            map.put(signalEx.getCode(),curValue);
                            influxdbServer.write(signalEx.getProfileCode(),terminal.getGatewayCode(),terminal.getCode(),null,map,signalEx.getNext());
                        }
                    }
                }
            }
        }
    }
}
